using System;
using System.IO;
using System.Net;

namespace Teele
{
    public class GetFile
    {
        public void Run()
        {
            try
            {
                // form the URI
                UriBuilder fullUri = new UriBuilder("http://www.geoape.com/clients/maanteeamet/?f=xml");

                // initialize a new WebRequest
                HttpWebRequest speedCamRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

                // set up the state object for the async request
                SpeedCamUpdateState speedCamState = new SpeedCamUpdateState();
                speedCamState.AsyncRequest = speedCamRequest;

                // start the asynchronous request
                speedCamRequest.BeginGetResponse(new AsyncCallback(HandleSpeedCamResponse),
                                             speedCamState);
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// State information for our BeginGetResponse async call
        /// </summary>
        public class SpeedCamUpdateState
        {
            public HttpWebRequest AsyncRequest { get; set; }
            public HttpWebResponse AsyncResponse { get; set; }
        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleSpeedCamResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                SpeedCamUpdateState speedCamState = (SpeedCamUpdateState)asyncResult.AsyncState;
                HttpWebRequest speedCamRequest = (HttpWebRequest)speedCamState.AsyncRequest;

                // end the async request
                speedCamState.AsyncResponse = (HttpWebResponse)speedCamRequest.EndGetResponse(asyncResult);

                Stream streamResult;

                streamResult = speedCamState.AsyncResponse.GetResponseStream();

                //StreamReader reader = new StreamReader(streamResult, System.Text.Encoding.GetEncoding("utf-8"));
                App.speedCamList = XmlParser.Parse(streamResult);
            }
            catch (Exception)
            {
            }
        }
    }
}